import os

from flask import Blueprint, request

from app import PASSERBY_UPLOAD_FOLDER
from app.Controllers.BaseController import BaseController
from app.Service.ChemometricsTutorialsServices.PowerAnalysisService import PowerAnalysisService
from app.Service.PasserByService import PasserByService

pa = Blueprint('/pa', __name__)


@pa.route('/')
def index():
    return BaseController().successData(msg="it's PA")


@pa.route('/getMetricCurvePlot', methods=['POST'])
def getMetricCurvePlot():
    PA = PowerAnalysisService().PACommomProcess()
    result = PowerAnalysisService().getMetricCurvePlot(PA)
    return result


@pa.route('/getMetricSpectrumPlot', methods=['POST'])
def getMetricSpectrumPlot():
    PA = PowerAnalysisService().PACommomProcess()
    result = PowerAnalysisService().getMetricSpectrumPlot(PA)
    return result


@pa.route('/getHeatmapPlot', methods=['POST'])
def getHeatmapPlot():
    PA = PowerAnalysisService().PACommomProcess()
    result = PowerAnalysisService().getHeatmapPlot(PA)
    return result


@pa.route('/getHeatmapForSignalPlot', methods=['POST'])
def getHeatmapForSignalPlot():
    PA = PowerAnalysisService().PACommomProcess()
    result = PowerAnalysisService().getHeatmapPlotForSignal(PA)
    return result


# 文件上传接口,根据dataType确定上传的文件是样本文件(data),标签文件(label),x轴坐标文件(coordinate)
@pa.route('/uploadFile', methods=['POST'])
def documentUploadFile():
    userId, projectId = PasserByService().getUserInfo()

    try:
        dataFiles = request.files['file']
    except:
        return BaseController().error(msg='未上传任何文件')

    saveDir = os.getcwd() + PASSERBY_UPLOAD_FOLDER + userId + "/" + projectId + "/"
    if not os.path.exists(saveDir):
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(saveDir)
    try:
        path, webPath = PasserByService().savefile(dataFiles, "PAFile", saveDir)
        data = dict(webPath=webPath)
        return BaseController().successData(data=data, msg='上传PA分析结果成功')
    except Exception as e:
        print(e)
        return BaseController().error(msg='上传出错')
